/**
 * Copyright 2009-2011 the original author or authors.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.myjung.generator;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.myjung.Myjung;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * @author Steve M. Jung
 */
public abstract class AbstractGenerateZipServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static Log logger = LogFactory.getLog(AbstractGenerateZipServlet.class);

	private static String tempPath;
	public String getTempPath() {
		return tempPath;
	}
	public void setTempPath(String value) {
		tempPath = value;
	}

	protected abstract void generate(String path, HttpServletRequest request) throws Exception;

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response);
	}
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String username = request.getParameter("_username");
		String fileName = request.getParameter("fileName");
		if (Myjung.isEmpty(username) || Myjung.isEmpty(fileName))
			throw new ServletException("notValid");

		if (!fileName.endsWith(".zip"))
			fileName += ".zip";
		String name = fileName.substring(0, fileName.lastIndexOf(".zip"));

		// 경로 설정
		String tmpPath = getTempPath();
		StringBuffer pathBuf = new StringBuffer(tmpPath);
		pathBuf.append("/user/").append(username);
		String userPath = pathBuf.toString();
		pathBuf.append("/").append(name);
		String path = pathBuf.toString();

		// 폴더 생성
		Myjung.deleteAll(userPath);
		new File(path).mkdirs();
		new File(new StringBuffer(path).append("/tmp.txt").toString()).createNewFile();

		try {
			generate(path, request);

		} catch (Exception e) {
			logger.error(e, e);
			try {
				Myjung.writeFileString(new StringBuffer(path).append("/error.txt").toString(), Myjung.toStackTraceString(e), true);
			} catch (Exception e1) {
				logger.error(e1, e1);
				throw new ServletException(e1);
			}
		} finally {
			try {
				// 압축
				Myjung.zip(path, null, null);

				// 보내기
				responseFile(getServletContext(), response, new File(path + ".zip"));

			} catch (ServletException e) {
				logger.error(e, e);
				throw e;
			} catch (IOException e) {
				logger.error(e, e);
				throw e;
			} catch (Exception e) {
				logger.error(e, e);
				throw new ServletException(e);
			}
			Myjung.deleteAll(userPath);
		}
	}

	private static void responseFile(ServletContext context, HttpServletResponse response, File file) throws Exception {
		OutputStream os = null;
		InputStream is = null;
		try {
			String fileName = file.getName();
			os = response.getOutputStream();
			String mimeType = context.getMimeType(fileName);
			response.setContentType(mimeType == null ? "application/octet-stream" : mimeType);
			response.setContentLength((int) file.length());
			response.setHeader("Content-Disposition", new StringBuffer("attachment; fileName=\"").append(fileName).append("\"").toString());
			is = new DataInputStream(new FileInputStream(file));
			int len;
			byte[] buffer = new byte[10240];
			while ((len = is.read(buffer, 0, buffer.length)) != -1)
				os.write(buffer, 0, len);
		} catch (Exception e) {
			throw e;
		} finally {
			if (is != null)
				is.close();
			if (os != null) {
				os.flush();
				os.close();
			}
		}
	}
}
